#include "StdAfx.h"

#include "Communicator.h"
#include "Avatar.h"
#include "Camera.h"
#include "GameManager.h"

Avatar::Avatar() : moveSpeed(4.0), rotateSpeed(1.0)
{
    init();
}

#if 0
Player::Player(int owner_id, int external_id, std::vector<unsigned char>& buffer) : Serializable(owner_id, external_id)
{
    init();
    // creating the object based on raw data 
    serialize(buffer);
}
#endif 

Avatar::~Avatar()
{
	
}

void Avatar::update( float dt )
{

}

void Avatar::init()
{
    gm = GameManager::getInstance();

    rotateSpeed = 5.0f;
    moveSpeed = 50.0f;

    eye = glm::vec3(0.0f, 0.0f, 0.0f);
    rotation = glm::vec3(20.0f, 135.0f, 0.0f);

    updateView();
}

void Avatar::moveForward(float dt)
{
    glm::vec3 forward(viewMatrix[0][2], viewMatrix[1][2], viewMatrix[2][2]);
    eye += dt * moveSpeed * forward;
    updateView();
}

void Avatar::moveLeft(float dt)
{
    glm::vec3 left(viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0]);
    eye += left * dt * moveSpeed;
    updateView();
}

void Avatar::updateView()
{
    viewMatrix = glm::rotate(glm::mat4(1.0), rotation[0], glm::vec3(1.0f, 0.0f, 0.0f));
    viewMatrix = glm::rotate(viewMatrix,	 rotation[1], glm::vec3(0.0f, 1.0f, 0.0f));
    viewMatrix = glm::rotate(viewMatrix,     rotation[2], glm::vec3(0.0f, 0.0f, 1.0f));
    viewMatrix = glm::translate(viewMatrix,eye);
}

void Avatar::rotateY(float dt)
{
    rotation[1] += dt * rotateSpeed;
    if(rotation[1] > 360.0f)
        rotation[1] -= 360.0f;
    else if(rotation[1] <= -360.0f)
        rotation[1] += 360.0f;

    updateView();
}

void Avatar::rotateX(float dt)
{
    rotation[0] += dt * rotateSpeed;
    if(rotation[0] > 360.0f)
        rotation[0] -= 360.0f;
    else if(rotation[0] <= -360.0f)
        rotation[0] += 360.0f;

    updateView();
}

glm::vec3 Avatar::getViewDirection()
{
    /*return glm::vec3(viewMatrix[2].x, viewMatrix[2].y, viewMatrix[2].z);*/

    return -glm::vec3(viewMatrix[0].z, viewMatrix[1].z, viewMatrix[2].z);
}

